#!/usr/bin/python2.4
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


"""Handler for the simple layer editor.

The simple layer editor allows users to quickly create a layer.
"""

__author__ = 'jasonstredwick@google.com (Jason Stredwick)'


# Disable 'Import not at top of file' lint error.
# pylint: disable-msg=C6204
try:
  import auto_import_fixer
except ImportError:
  pass  # This will fail on unittest, ok to pass.

from layer.models import layer_simple

import simplejson

# Disable 'Import not at top of file' lint error.
# pylint: disable-msg=C6204
try:
  from google.appengine.ext import webapp
  from google.appengine.ext.webapp.util import run_wsgi_app
except ImportError:
  from google.appengine.ext import webapp
  from google.appengine.ext.webapp.util import run_wsgi_app


class Data(webapp.RequestHandler):
  """Handles the retrieval of data for the simple editor."""

  def get(self):
    """Handles a get request, redirects to the post request."""
    self.post()

  def post(self):
    """Handles a post request.

    Returns the layer manifest for the specified simple layer.
    """
    data = layer_simple.GetData(self.request.get('name'))
    output = simplejson.dumps(data)
    self.response.out.write(output)


class Get(webapp.RequestHandler):
  """Handles the retrieval simple layer's manifest."""

  def get(self):
    """Handles a get request, redirects to the post request."""
    self.post()

  def post(self):
    """Handles a post request.

    Returns the layer manifest for the specified simple layer.
    """
    output = layer_simple.GetManifest(self.request.get('name'))
    output = simplejson.dumps(output)
    self.response.out.write(output)


class Update(webapp.RequestHandler):
  """Handles request to update a simple layer."""

  def get(self):
    """Handles a get request, redirects to the post request."""
    self.post()

  def post(self):
    """Handles a post request.

    Returns:
      The rendered page for the simple editor for a new layer.
    """
    output = 'Failed'
    data_string = self.request.get('data')
    serverUrl = self.request.host_url
    if data_string:
      try:
        data = simplejson.loads(data_string)
        # Only the name is required, the other keys will update default values
        # if missing.
        url = layer_simple.Update(data['name'], serverUrl,
                                  data['backgroundJs'],
                                  data['contentCss'], data['contentJs'],
                                  data['ondemand'], data['state'])
        if url:
          output = url
      except Exception or StandardError:
        # If an exception is thrown then 'Failed' will be sent to the client.
        pass

    self.response.out.write(output)


def main():
  application = webapp.WSGIApplication([('/layer/simple/data', Data),
                                        ('/layer/simple/get', Get),
                                        ('/layer/simple/update', Update)],
                                       debug=True)
  run_wsgi_app(application)

  return


if __name__ == '__main__':
  main()

